package com.fintech.pangu.security.oauth2.sso.client.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpSession;

/**
 * zuul网关环境下，用于将session中携带用户基本信息的JWT放在转发后的请求头中
 */
public class JWTTransferZuulFilter extends ZuulFilter {

    private static final String USER_DETAIL_JWT = "USER_DETAIL_JWT";

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 11;
    }

    /**
     * 如果session中的userDetails信息不为空，则通过此Filter
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpSession httpSession = ctx.getRequest().getSession();
        String userDetailsJWT = (String) httpSession.getAttribute("userDetails");
        if (userDetailsJWT != null) {
            ctx.set(USER_DETAIL_JWT, userDetailsJWT);
            return true;
        }
        return false;
    }

    /**
     * 将USER_DETAIL_JWT放入转发后的请求头中
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.addZuulRequestHeader("xToken", ctx.get(USER_DETAIL_JWT) + "");
        return null;
    }
}
